//
//  KXHomeViewController.swift
//  KXBook
//
//  Created by  on 2022/9/7.
//

import UIKit

class KXHomeViewController: KXViewController {
    @IBOutlet var outNum: UILabel!
    @IBOutlet var inNum: UILabel!
    @IBOutlet var tableView: UITableView!
    @IBOutlet var btn: UIButton!
    @IBOutlet var dateBtn: UIButton!
    var rightBtn:UIButton?
    var startStamp = 0
    var endStamp = 0
    var array = [[String:[KXRecord]]]()
    var totalpay = CGFloat(0)
    var totalIn = CGFloat(0)
    var moneyArray = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = LS("明细")
        self.backBtn?.isHidden = true
        
        self.rightBtn = UIButton(type: .custom)
        self.rightBtn?.tag = 203
        self.rightBtn?.frame = CGRect(x: 0, y: kUIStatusBarHeight + 5, width: 60, height: 34)
        self.rightBtn?.addTarget(self, action: #selector(actionForBtn), for: .touchUpInside)
        self.rightBtn?.setImage(UIImage(named:"grid")?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.rightBtn?.setTitle(LS("类别"), for:.normal)
        self.rightBtn?.setTitleColor(.black, for: .normal)
        self.rightBtn?.titleLabel?.font = font(12)
        
        let backItem = UIBarButtonItem(customView: self.rightBtn!)
        self.navigationItem.rightBarButtonItem = backItem
        self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.black, .font:font(18)]
        
        self.tableView.register(KXHomeCell.nib(), forCellReuseIdentifier: KXHomeCell.ID())
        
        let stamp = NSDate.currentTimeStamp("yyyy/MM/dd").intValue()
        let date = NSDate.dateOfStamp(stamp)
        self.startStamp = NSDate.tranToStamp("\(date.year!)/\(date.month!)/1", "yyyy/MM/dd").intValue()
        self.endStamp = stamp
        self.loadData()
    }
    @IBAction func actionForBtn(_ sender: UIButton) {
        switch sender.tag{
        case 201:///日期
            let vc = KXDateViewController()
            vc.stamp = self.startStamp
            vc.endStamp = self.endStamp
            vc.startStamp = self.startStamp
            weak var weakself = self
            vc.block = {(startStamp , endStamp) in
                weakself?.startStamp = startStamp
                weakself?.endStamp = endStamp
                weakself?.loadData()
            }
            self.push(vc, true)
        case 202:///添加
            let vc = KXAddViewController()
            self.push(vc, true)
        case 203:
            let vc = KXListViewController()
            self.push(vc, true)
        default:
            break
        }
    }
    
    
    @objc func loadData(){
        if self.currentVC().className == "KXHomeViewController"{
            Toast.startHud(LS("获取数据中..."))
        }
        let startDate = NSDate.dateOfStamp(self.startStamp)
        let endDate = NSDate.dateOfStamp(self.endStamp)
        let str = String(format: LS("%d年%d月"), startDate.year!, startDate.month!)
        self.dateBtn.setTitle(str, for: .normal)
        
        self.array = [[String:[KXRecord]]]()
        self.totalpay = CGFloat(0)
        self.totalIn = CGFloat(0)
        self.moneyArray.removeAll()
        
        let group = DispatchGroup()
        let queue = DispatchQueue.global()

        var start = NSDate.stamp(self.startStamp, 0)
        while start <= self.endStamp {
            let date = NSDate.dateOfStamp(start)
            start += 24 * 3600
            
            let str = String(format: "where %@=%@ and %@=%@ and %@=%@ and %@=%@", bg_sqlKey("userID"),bg_sqlValue(APP.user.id),bg_sqlKey("year"),bg_sqlValue("\(date.year!)"),bg_sqlKey("month"),bg_sqlValue("\(date.month!)"),bg_sqlKey("day"),bg_sqlValue("\(date.day!)"))
            group.enter()
            queue.async(group: group, execute: {
                KXRecord.bg_findAsync(nil, where: str) { success in
                    if success?.count ?? 0 > 0 {
                        let key = String(format:LS("%d月%d日"), date.month!, date.day!)
                        let value = success as? [KXRecord] ?? [KXRecord]()
                        let dict = [key:value]
                        self.array.append(dict)
                        
                        var p = CGFloat(0)
                        var i = CGFloat(0)
                        for record in value {
                            if record.type.isPay == 1 {
                                p += CGFloat((record.money as NSString).floatValue)
                                self.totalpay += p
                            }else{
                                i += CGFloat((record.money as NSString).floatValue)
                                self.totalIn += i
                            }
                        }
                        let s = String(format:LS("支出:%.1f  收入:%.1f"), p,i)
                        self.moneyArray.append(s)
                    }
                    group.leave()
                }
            })
        }
        
        group.notify(queue: .main) {
            Toast.stopHud()
            self.outNum.text = LS("¥")+"\(self.totalpay)"
            self.inNum.text = LS("¥")+"\(self.totalIn)"
            self.tableView.reloadData()
        }
    }
    func edit(_ index:IndexPath, _ delete:Bool){
        let dict = self.array[index.section]
        let values = dict.values.first ?? [KXRecord]()
        let model = values[index.row]
        let str = String(format: "where %@=%@ and %@=%@", bg_sqlKey("userID"),bg_sqlValue(APP.user.id),bg_sqlKey("stamp"),bg_sqlValue("\(model.stamp)"))
        if delete{
            KXRecord.bg_deleteAsync(nil, where: str) { success in
                DispatchQueue.main.async {
                    self.loadData()
                }
            }
        }else{
            let vc = KXAddViewController()
            let array = self.array[index.section].values.first ?? [KXRecord]()
            vc.model = array[index.row]
            self.push(vc, true)
        }
    }
}

extension KXHomeViewController{
    override func addNotify() {
        NotifyTool.add(self, #selector(loadData), NotifyName.updateRecord)
        NotifyTool.add(self, #selector(loadData), NotifyName.updateUser)
    }
}
//MARK: - UITableViewDataSource
extension KXHomeViewController : UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.array.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let array = self.array[section].values.first ?? [KXRecord]()
        return array.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: KXHomeCell.ID()) as! KXHomeCell
        let array = self.array[indexPath.section].values.first ?? [KXRecord]()
        cell.model = array[indexPath.row]
        return cell
    }
    
}
//MARK: - UITableViewDelegate
extension KXHomeViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = KXDetailController()
        let array = self.array[indexPath.section].values.first ?? [KXRecord]()
        vc.model = array[indexPath.row]
        self.push(vc, true)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
    {
        return 40
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
    {
        let view = UIView(frame:CGRect(x:0, y:0, width:kUIScreenWidth - 32, height:40))
        let header = KXHomeHeader.loadFromXIB() as! KXHomeHeader
        header.translatesAutoresizingMaskIntoConstraints = true
        header.frame = view.frame
        header.date.text = self.array[section].keys.first!
        header.money.text = self.moneyArray[section]
        view.addSubview(header)
        return view
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .none
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        weak var weakself = self
        if #available(iOS 11.0, *){
            let edit = UIContextualAction(style:.normal, title:LS("编辑")) { action, view, handler in
                weakself?.edit(indexPath, false)
            }
            edit.backgroundColor = "#E27BC1".color()
            let delete = UIContextualAction(style:.normal, title:LS("删除")) { action, view, handler in
                weakself?.edit(indexPath, true)
            }
            delete.backgroundColor = "#ED593B".color()
            let config = UISwipeActionsConfiguration(actions: [delete,edit])
            config.performsFirstActionWithFullSwipe = false
            return config
        }
    }
}
